<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900 py-8">
    <div class="container mx-auto px-4">
      
      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center min-h-[60vh]">
        <div class="loader"></div>
      </div>
      
      <!-- 错误信息 -->
      <div v-else-if="error" class="text-center py-20">
        <div class="text-red-500 text-xl mb-4">{{ error }}</div>
        <router-link to="/servers" class="text-blue-600 dark:text-blue-400 hover:underline">
          返回 Server 列表
        </router-link>
      </div>

      <!--  Server 详情内容 -->
      <template v-else>
        <!-- 安全声明 -->
        <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-4">
          <div class="flex">
            <div class="flex-shrink-0">
              <svg class="h-5 w-5 text-yellow-600 dark:text-yellow-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
              </svg>
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-yellow-800 dark:text-yellow-200">
                {{ server.is_internal ? '内部MCP Server声明' : '外部社区MCP Server声明' }}
              </h3>
              <div class="mt-3 text-sm text-yellow-700 dark:text-yellow-300">
                <p v-if="server.is_internal">
                  该MCP Server由华为 <span class="font-semibold">{{ server.provider }}</span> 提供和维护。如有安装、使用问题或需要技术支持，请直接联系该提供者获取帮助。
                </p>
                <p v-else>
                  该MCP Server来源于外部互联网开源社区，安装和使用请参考社区提供的文档。在使用前请仔细评估是否存在外网访问和安全风险，避免产生敏感信息泄露。建议在隔离环境中测试后再正式使用。
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 头部信息 -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md overflow-hidden mb-4">
          <div class="p-6 md:p-8">
            <!-- 返回按钮 -->
            <div class="mb-4">
              <button @click="goBack" class="inline-flex items-center text-gray-600 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                </svg>
                <span>返回</span>
              </button>
            </div>
            <div class="flex flex-col md:flex-row md:items-center justify-between mb-4">
              <div class="w-full">
                <div class="flex items-center mb-2 justify-between">
                  <h1 class="text-2xl md:text-3xl font-bold text-gray-900 dark:text-white">
                    {{ activeDocLang === 'cn' && server.name_cn ? server.name_cn : server.name }}
                  </h1>
                  <!-- 中英文切换按钮 -->
                  <div v-if="(server.name_cn && server.name) || (server.description_cn && server.description)" class="inline-flex rounded-md shadow-sm">
                    <button
                      @click="activeDocLang = 'cn'"
                      :class="[
                        activeDocLang === 'cn' 
                          ? 'bg-blue-600 text-white' 
                          : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600',
                        'px-3 py-1 text-xs font-medium rounded-l-md border border-gray-300 dark:border-gray-600'
                      ]"
                    >
                      中文
                    </button>
                    <button
                      @click="activeDocLang = 'en'"
                      :class="[
                        activeDocLang === 'en' 
                          ? 'bg-blue-600 text-white' 
                          : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600',
                        'px-3 py-1 text-xs font-medium rounded-r-md border border-gray-300 dark:border-gray-600 border-l-0'
                      ]"
                    >
                      原文
                    </button>
                  </div>
                </div>

                
                <div class="mb-6 text-sm text-gray-500 dark:text-gray-400">
                  <span class="font-bold">{{ server.provider }}</span>
                </div>
                
                <p class="text-gray-600 dark:text-gray-300 mb-4">
                  {{ activeDocLang === 'cn' && server.description_cn ? server.description_cn : server.description }}
                </p>

                <!-- 来源信息 -->
                <div v-if="server.from_site || server.from_site_url" class="mb-6 text-sm text-gray-500 dark:text-gray-400">
                  <span>源码地址：</span>
                  <a 
                    v-if="server.from_site_url" 
                    :href="server.from_site_url" 
                    target="_blank" 
                    class="text-blue-600 dark:text-blue-400 hover:underline"
                  >
                    {{ server.from_site_url }}
                  </a>
                </div>

                <!-- 标签和分类 -->
                <div class="flex flex-wrap gap-2">
                  <span 
                    v-if="server.is_internal"
                    class="inline-flex items-center px-2.5 py-0.5 text-xs font-medium rounded-full bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"
                  >
                    内部
                  </span>
                  <span 
                    v-if="server.is_official"
                    class="inline-flex items-center px-2.5 py-0.5 text-xs font-medium rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"
                  >
                    官方
                  </span>

                  <!-- 分类标签 -->
                  <span 
                    v-for="(category, idx) in (activeDocLang === 'cn' && server.category_cn && server.category_cn.length > 0 ? server.category_cn : server.category)" 
                    :key="'cat-'+idx"
                    class="inline-flex items-center px-2.5 py-0.5 text-xs font-medium rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
                  >
                    {{ category }}
                  </span>

                  <!-- 标签 -->
                  <span 
                    v-for="(tag, idx) in server.tags" 
                    :key="'tag-'+idx"
                    class="inline-flex items-center px-2.5 py-0.5 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"
                  >
                    {{ tag }}
                  </span>

                  <!-- 开发语言 -->
                  <span class="inline-flex items-center px-2.5 py-0.5 text-xs font-medium rounded-full bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
                  >
                    {{ server.dev_language }}
                  </span>
                </div>

              </div>
              <div class="mt-4 md:mt-0 space-x-2">
                <router-link 
                  v-if="canEdit" 
                  :to="`/edit-server/${id}`" 
                  class="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" viewBox="0 0 20 20" fill="currentColor">
                    <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
                  </svg>
                  编辑
                </router-link>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 标签页内容区域 -->
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md overflow-hidden mb-8">       
          
            <!-- 标签页 -->
            <div class="mt-2">
              <div class="border-b border-gray-200 dark:border-gray-700">
                <nav class="flex -mb-px space-x-8 overflow-x-auto" aria-label="Tabs">
                  <button 
                    @click="activeTab = 'docs'" 
                    :class="[
                      activeTab === 'docs' 
                        ? 'border-blue-500 text-blue-600 dark:text-blue-400 font-medium' 
                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300',
                      'whitespace-nowrap py-4 px-3 border-b-2 text-sm flex items-center'
                    ]"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    文档说明
                  </button>
                  <button 
                    @click="activeTab = 'config'" 
                    :class="[
                      activeTab === 'config' 
                        ? 'border-blue-500 text-blue-600 dark:text-blue-400 font-medium' 
                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300',
                      'whitespace-nowrap py-4 px-3 border-b-2 text-sm flex items-center'
                    ]"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    配置信息
                  </button>
                  <button 
                    v-if="false"
                    @click="activeTab = 'comments'" 
                    :class="[
                      activeTab === 'comments' 
                        ? 'border-blue-500 text-blue-600 dark:text-blue-400 font-medium' 
                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:border-gray-300',
                      'whitespace-nowrap py-4 px-3 border-b-2 text-sm flex items-center'
                    ]"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
                    </svg>
                    评论
                  </button>
                </nav>
              </div>
            </div>

          <div class="p-6">
            <!-- 文档标签页内容 -->
            <div v-if="activeTab === 'docs'" class="py-2">
              <!-- 华为内部使用文档 -->
              <div v-if="server.internal_doc_url" class="mb-6 bg-green-100 dark:bg-green-800/50 rounded-lg p-4">
                <div class="flex items-center text-sm text-green-500 dark:text-green-400">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <span>华为内部安装使用说明可参考：</span>
                  <a 
                    :href="server.internal_doc_url" 
                    target="_blank" 
                    class="ml-1 text-blue-600 dark:text-blue-400 hover:underline"
                  >
                    {{ server.internal_doc_url }}
                  </a>
                </div>
              </div>

              <!-- 中文README内容 -->
              <div v-if="activeDocLang === 'cn' && server.readme_cn" class="prose dark:prose-invert max-w-none">
                <div v-html="compiledReadmeCn"></div>
              </div>
              
              <!-- 英文README内容 -->
              <div v-else-if="activeDocLang === 'en' && server.readme" class="prose dark:prose-invert max-w-none">
                <div v-html="compiledReadme"></div>
              </div>
              
              <!-- 无README文档 -->
              <div v-else class="text-center py-8 border border-dashed border-gray-300 dark:border-gray-700 rounded-lg">
                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                <h3 class="mt-2 text-sm font-medium text-gray-900 dark:text-white">暂无文档</h3>
                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">此 Server 暂未提供文档说明</p>
              </div>
            </div>

            <!-- 配置标签页内容 -->
            <div v-if="activeTab === 'config'" class="py-2">
              <!-- 服务器配置 -->
              <div v-if="server.server_config" class="mb-6">
                <div class="flex justify-between items-center mb-3">
                  <h2 class="text-xl font-semibold text-gray-900 dark:text-white">服务器配置</h2>
                </div>
                <div class="bg-gray-800 rounded-lg overflow-hidden">
                  <div class="p-4">
                    <pre class="text-green-400 font-mono text-sm whitespace-pre-wrap relative">
<button class="copy-btn absolute top-2 right-2 text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white py-1 px-2 rounded" @click="copyToClipboard(formatJSON(server.server_config))">复制</button>{{ formatJSON(server.server_config) }}</pre>
                  </div>
                </div>
              </div>

              <!-- 环境变量配置 -->
              <div v-if="server.env_schema && Object.keys(server.env_schema).length > 0" class="mb-6">
                <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-3">环境变量</h2>
                <div class="bg-gray-50 dark:bg-gray-800 rounded-lg overflow-hidden">
                  <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-100 dark:bg-gray-700">
                      <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">变量名</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">类型</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">描述</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">必填</th>
                      </tr>
                    </thead>
                    <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                      <tr v-for="(schema, key) in server.env_schema.properties || {}" :key="key" class="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">{{ key }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                          <span class="px-2 py-1 text-xs rounded bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300">
                            {{ schema.type }}
                          </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">{{ schema.description }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                          <span v-if="server.env_schema.required && server.env_schema.required.includes(key)" class="text-red-600 dark:text-red-400">是</span>
                          <span v-else class="text-gray-500 dark:text-gray-400">否</span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
            
            <!-- 评论标签页内容 -->
            <div v-if="activeTab === 'comments'" class="py-2">
              <div v-if="loadingComments" class="flex justify-center py-12">
                <div class="loader"></div>
              </div>
              <div v-else-if="commentsError" class="text-red-500 py-8 text-center">
                {{ commentsError }}
              </div>
              <div v-else>
                <div v-if="comments.length === 0" class="text-gray-500 dark:text-gray-400 py-8 text-center">
                  暂无评论，成为第一个评论的人吧！
                </div>
                <div v-else class="space-y-6">
                  <div v-for="comment in comments" :key="comment.id" class="border-b border-gray-200 dark:border-gray-700 pb-6 last:border-0">
                    <div class="flex items-start">
                      <div class="flex-shrink-0 mr-3">
                        <div class="h-10 w-10 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
                          <span class="text-gray-600 dark:text-gray-300 font-medium">{{ comment.author.charAt(0) }}</span>
                        </div>
                      </div>
                      <div class="flex-1">
                        <div class="flex items-center justify-between mb-1">
                          <div class="font-medium text-gray-900 dark:text-white">{{ comment.author }}</div>
                          <div class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(comment.createdAt) }}</div>
                        </div>
                        <div class="text-gray-800 dark:text-gray-200">{{ comment.content }}</div>
                        <div class="mt-2">
                          <button @click="showReplyForm(comment.id)" class="text-sm text-blue-600 dark:text-blue-400 hover:underline">回复</button>
                        </div>
                        
                        <!-- 回复表单 -->
                        <div v-if="replyToId === comment.id" class="mt-3">
                          <textarea 
                            v-model="replyContent"
                            class="w-full p-2 border border-gray-300 dark:border-gray-600 rounded-md text-gray-900 dark:text-white bg-white dark:bg-gray-700"
                            placeholder="写下你的回复..."
                            rows="2"
                          ></textarea>
                          <div class="mt-2 flex justify-end space-x-2">
                            <button 
                              @click="cancelReply"
                              class="px-3 py-1 text-sm text-gray-600 dark:text-gray-300 hover:text-gray-800 dark:hover:text-white"
                            >
                              取消
                            </button>
                            <button 
                              @click="submitReply(comment.id)"
                              class="px-3 py-1 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700"
                              :disabled="!replyContent.trim()"
                            >
                              提交回复
                            </button>
                          </div>
                        </div>
                        
                        <!-- 回复列表 -->
                        <div v-if="comment.replies && comment.replies.length > 0" class="mt-3 pl-4 border-l-2 border-gray-200 dark:border-gray-700 space-y-4">
                          <div v-for="reply in comment.replies" :key="reply.id" class="pt-2">
                            <div class="flex items-start">
                              <div class="flex-shrink-0 mr-3">
                                <div class="h-8 w-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
                                  <span class="text-gray-600 dark:text-gray-300 font-medium text-sm">{{ reply.author.charAt(0) }}</span>
                                </div>
                              </div>
                              <div class="flex-1">
                                <div class="flex items-center justify-between mb-1">
                                  <div class="font-medium text-gray-900 dark:text-white">{{ reply.author }}</div>
                                  <div class="text-xs text-gray-500 dark:text-gray-400">{{ formatDate(reply.createdAt) }}</div>
                                </div>
                                <div class="text-gray-800 dark:text-gray-200 text-sm">{{ reply.content }}</div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 添加评论 -->
                <div class="mt-8 border-t border-gray-200 dark:border-gray-700 pt-6">
                  <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">添加评论</h3>
                  <div v-if="!isAuthenticated">
                    <p class="text-gray-600 dark:text-gray-400 mb-2">
                      请先登录后再进行评论
                    </p>
                    <router-link to="/login" class="text-blue-600 dark:text-blue-400 hover:underline">
                      去登录
                    </router-link>
                  </div>
                  <div v-else>
                    <textarea 
                      v-model="commentContent"
                      class="w-full p-3 border border-gray-300 dark:border-gray-600 rounded-md text-gray-900 dark:text-white bg-white dark:bg-gray-700"
                      placeholder="写下你的评论..."
                      rows="3"
                    ></textarea>
                    <div class="mt-3 flex justify-end">
                      <button 
                        @click="submitComment"
                        class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
                        :disabled="!commentContent.trim()"
                      >
                        发表评论
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import { useThemeStore } from '@/stores/theme'
import { marked } from 'marked'
import { getServerById, getServerReadme } from '@/api/server'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const themeStore = useThemeStore()
const id = ref(route.params.id as string)

// 主题相关
const isDarkMode = computed(() => themeStore.darkMode)
const toggleTheme = () => themeStore.toggleTheme()

//  Server 详情数据
const server = ref<any>({})
const loading = ref(true)
const error = ref<string | null>(null)

// 标签页相关数据
const activeTab = ref('docs') // 默认显示文档标签页 
const activeDocLang = ref('cn') // 默认显示中文文档

// README相关数据
const readme = ref<string | null>(null)
const loadingReadme = ref(false)
const readmeError = ref<string | null>(null)
const renderedReadme = computed(() => {
  if (!readme.value) return ''
  // 使用marked渲染Markdown内容，并增加样式类
  return marked(readme.value, {
    gfm: true,
    breaks: true,
    sanitize: false,
    // 确保生成的HTML符合当前主题样式
    renderer: createRenderer()
  })
})

// 安装指南相关数据
const renderedInstallGuide = computed(() => {
  if (!server.value?.installationGuide) return ''
  // 使用相同的渲染器来保持风格一致
  return marked(server.value.installationGuide, {
    gfm: true,
    breaks: true,
    sanitize: false,
    renderer: createRenderer()
  })
})

// 评论相关数据
const comments = ref<any[]>([])
const loadingComments = ref(false)
const commentsError = ref<string | null>(null)
const commentContent = ref('')
const replyContent = ref('')
const replyToId = ref<number | null>(null)

// 标签页相关数据
const tabs = [
  { id: 'readme', label: 'README' },
  { id: 'configuration', label: '配置选项' },
  { id: 'installation', label: '安装指南' },
  { id: 'comments', label: '评论' }
]

// 计算属性
const isAuthenticated = computed(() => authStore.isAuthenticated)
const canEdit = computed(() => {
  // 根据实际情况定义编辑权限，这里简单示例
  return isAuthenticated.value && (
    authStore.user?.isAdmin || 
    (server.value?.createdById === authStore.user?.id)
  )
})

// 获取 Server 详情
const fetchServerDetail = async () => {
  loading.value = true
  error.value = null
  
  try {
    // 使用API服务获取详情
    server.value = await getServerById(id.value)
  } catch (err) {
    console.error('获取 Server 详情失败:', err)
    error.value = '无法加载 Server 详情，请稍后再试'
  } finally {
    loading.value = false
  }
}

// 获取README
const fetchReadme = async () => {
  if (!server.value?.id) return
  
  // 如果服务器对象中已经包含README，直接使用
  if (server.value.readme) {
    readme.value = server.value.readme
    return
  }
  
  loadingReadme.value = true
  readmeError.value = null
  
  try {
    // 使用API服务获取README
    const response = await getServerReadme(id.value)
    readme.value = response.content
  } catch (err) {
    console.error('获取README失败:', err)
    readmeError.value = '无法加载README，请稍后再试'
  } finally {
    loadingReadme.value = false
  }
}

// 获取评论
const fetchComments = async () => {
  if (!server.value?.id) return
  
  loadingComments.value = true
  commentsError.value = null
  
  try {
    // 这里应该根据实际API地址调整
    const response = await axios.get(`/api/servers/${id.value}/comments`)
    comments.value = response.data.results
  } catch (err) {
    console.error('获取评论失败:', err)
    commentsError.value = '无法加载评论，请稍后再试'
    // 开发环境下使用模拟数据
    if (import.meta.env.DEV) {
      comments.value = [
        {
          id: 1,
          author: '张三',
          content: '这个 Server 非常好用，文档清晰，安装简单。',
          createdAt: '2023-06-15T08:30:00Z',
          replies: [
            {
              id: 3,
              author: '管理员',
              content: '感谢您的反馈！我们将继续改进。',
              createdAt: '2023-06-15T09:15:00Z'
            }
          ]
        },
        {
          id: 2,
          author: '李四',
          content: '我在安装过程中遇到了一些问题，有没有详细的故障排除指南？',
          createdAt: '2023-06-14T14:20:00Z',
          replies: []
        }
      ]
      commentsError.value = null
    }
  } finally {
    loadingComments.value = false
  }
}

// 显示回复表单
const showReplyForm = (commentId: number) => {
  if (!isAuthenticated.value) {
    router.push('/login')
    return
  }
  
  replyToId.value = commentId
  replyContent.value = ''
}

// 取消回复
const cancelReply = () => {
  replyToId.value = null
  replyContent.value = ''
}

// 提交回复
const submitReply = async (commentId: number) => {
  if (!replyContent.value.trim() || !isAuthenticated.value) return
  
  try {
    // 这里应该根据实际API地址调整
    await axios.post(`/api/comments/${commentId}/replies`, {
      content: replyContent.value
    })
    
    // 刷新评论
    await fetchComments()
    
    // 重置表单
    replyToId.value = null
    replyContent.value = ''
  } catch (err) {
    console.error('提交回复失败:', err)
    alert('提交回复失败，请稍后再试')
  }
}

// 提交评论
const submitComment = async () => {
  if (!commentContent.value.trim() || !isAuthenticated.value) return
  
  try {
    // 这里应该根据实际API地址调整
    await axios.post(`/api/servers/${id.value}/comments`, {
      content: commentContent.value
    })
    
    // 刷新评论
    await fetchComments()
    
    // 重置表单
    commentContent.value = ''
  } catch (err) {
    console.error('提交评论失败:', err)
    alert('提交评论失败，请稍后再试')
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 复制到剪贴板
const copyToClipboard = (text: string) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      alert('已复制到剪贴板')
    })
    .catch(err => {
      console.error('复制失败:', err)
      alert('复制失败，请手动复制')
    })
}

// 创建自定义渲染器
function createRenderer() {
  const renderer = new marked.Renderer()
  
  // 自定义链接渲染
  renderer.link = function(href, title, text) {
    return `<a href="${href}" title="${title || ''}" target="_blank" rel="noopener noreferrer" class="text-blue-600 dark:text-blue-400 hover:underline">${text}</a>`
  }
  
  // 自定义代码块渲染
  renderer.code = function(code, language) {
    const langClass = language ? ` class="language-${language}"` : '';
    return `<pre class="relative bg-gray-800 rounded-lg p-4 overflow-x-auto"><button class="copy-btn absolute top-2 right-2 text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white py-1 px-2 rounded" onclick="navigator.clipboard.writeText(this.parentElement.querySelector('code').innerText)">复制</button><code${langClass}>${code}</code></pre>`;
  }
  
  // 自定义标题渲染
  renderer.heading = function(text, level) {
    const classes = [
      'font-bold text-gray-900 dark:text-white my-4', // 基础样式
      level === 1 ? 'text-2xl' : '',
      level === 2 ? 'text-xl' : '',
      level === 3 ? 'text-lg' : '',
      level === 4 ? 'text-base' : '',
      level === 5 ? 'text-sm' : '',
      level === 6 ? 'text-xs' : ''
    ].filter(Boolean).join(' ')
    
    return `<h${level} class="${classes}">${text}</h${level}>`
  }
  
  // 自定义表格渲染
  renderer.table = function(header, body) {
    return `<div class="overflow-x-auto my-4">
      <table class="min-w-full divide-y divide-gray-300 dark:divide-gray-700">
        <thead class="bg-gray-50 dark:bg-gray-800">${header}</thead>
        <tbody class="divide-y divide-gray-200 dark:divide-gray-700 bg-white dark:bg-gray-900">${body}</tbody>
      </table>
    </div>`
  }
  
  // 自定义表格行渲染
  renderer.tablerow = function(content) {
    return `<tr class="hover:bg-gray-50 dark:hover:bg-gray-800">${content}</tr>`
  }
  
  // 自定义表格单元格渲染
  renderer.tablecell = function(content, flags) {
    const type = flags.header ? 'th' : 'td'
    const classes = flags.header 
      ? 'px-6 py-3 text-left text-xs font-medium text-gray-700 dark:text-gray-300 uppercase tracking-wider'
      : 'px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400'
    return `<${type} class="${classes}">${content}</${type}>`
  }
  
  // 自定义列表渲染
  renderer.list = function(body, ordered, start) {
    const type = ordered ? 'ol' : 'ul'
    const startAttr = ordered && start !== 1 ? ` start="${start}"` : ''
    const classes = ordered
      ? 'list-decimal pl-8 my-4 text-gray-700 dark:text-gray-300'
      : 'list-disc pl-8 my-4 text-gray-700 dark:text-gray-300'
    return `<${type}${startAttr} class="${classes}">${body}</${type}>`
  }
  
  // 自定义列表项渲染
  renderer.listitem = function(text) {
    return `<li class="mb-2">${text}</li>`
  }
  
  // 自定义段落渲染
  renderer.paragraph = function(text) {
    return `<p class="mb-4 text-gray-700 dark:text-gray-300">${text}</p>`
  }
  
  // 自定义水平线渲染
  renderer.hr = function() {
    return `<hr class="my-6 border-t border-gray-300 dark:border-gray-700" />`
  }
  
  // 自定义图片渲染
  renderer.image = function(href, title, text) {
    return `<img src="${href}" alt="${text}" title="${title || ''}" class="max-w-full h-auto rounded my-4" />`
  }
  
  // 自定义加粗文本渲染
  renderer.strong = function(text) {
    return `<strong class="font-bold text-gray-900 dark:text-white">${text}</strong>`
  }
  
  // 自定义斜体文本渲染
  renderer.em = function(text) {
    return `<em class="italic text-gray-800 dark:text-gray-200">${text}</em>`
  }
  
  return renderer
}

// 解析并编译Markdown
const compiledReadme = computed(() => {
  if (!server.value.readme) return ''
  // 使用marked渲染Markdown内容，并增加样式类
  return marked(server.value.readme, {
    gfm: true,
    breaks: true,
    sanitize: false,
    // 确保生成的HTML符合当前主题样式
    renderer: createRenderer()
  })
})

const compiledReadmeCn = computed(() => {
  if (!server.value.readme_cn) return ''
  // 使用marked渲染Markdown内容，并增加样式类
  return marked(server.value.readme_cn, {
    gfm: true,
    breaks: true,
    sanitize: false,
    // 确保生成的HTML符合当前主题样式
    renderer: createRenderer()
  })
})

// 格式化JSON
const formatJSON = (jsonString) => {
  try {
    // 尝试将字符串解析为JSON对象
    const obj = typeof jsonString === 'object' ? jsonString : JSON.parse(jsonString)
    // 将对象转换回格式化的JSON字符串
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    // 如果解析失败，返回原始字符串
    return jsonString
  }
}

// 生命周期钩子
onMounted(async () => {
  await fetchServerDetail()
  
  if (server.value?.id) {
    fetchReadme()
    // fetchComments()
  }
})

// 返回上一页方法
const goBack = () => {
  // 检查上一页是否来自当前网站
  if (window.history.length > 1 && document.referrer.includes(window.location.hostname)) {
    router.back()
  } else {
    // 如果是直接通过网址进入的或来自其他网站，则返回到列表页面
    router.push('/servers')
  }
}

</script>

<style scoped>
.loader {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 4px solid #3498db;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 移除之前的标样式，现在在渲染器中直接应用样式 */
/* :deep(.dark .prose) {
  color: #e2e8f0;
}

:deep(.dark .prose h1),
:deep(.dark .prose h2),
:deep(.dark .prose h3),
:deep(.dark .prose h4) {
  color: white;
}

:deep(.dark .prose a) {
  color: #60a5fa;
}

:deep(.dark .prose code) {
  color: #e2e8f0;
  background: #374151;
} */

/* 添加全局markdown样式 */
:deep(pre) {
  margin: 1em 0;
  border-radius: 0.375rem;
  overflow-x: auto;
  position: relative;
  padding-top: 1em !important;
}

:deep(pre code) {
  display: block;
  padding: 1em;
}

/* 代码块复制按钮样式 */
:deep(pre)::before {
  content: "";
}

:deep(pre) {
  margin: 1em 0;
  border-radius: 0.375rem;
  overflow-x: auto;
  position: relative;
  padding-top: 1em !important;
}

:deep(pre .copy-btn) {
  opacity: 0;
  transition: opacity 0.2s;
}

:deep(pre:hover .copy-btn) {
  opacity: 1;
}

:deep(blockquote) {
  border-left: 4px solid #e2e8f0;
  padding-left: 1rem;
  color: #6b7280;
  margin: 1.5em 0;
}

:deep(.dark blockquote) {
  border-left-color: #4b5563;
  color: #9ca3af;
}

:deep(a) {
  text-decoration: none;
}

:deep(a:hover) {
  text-decoration: underline;
}

:deep(img) {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 1.5em auto;
  border-radius: 0.375rem;
}

:deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 1.5em 0;
}

/* 添加暗色主题的代码高亮样式 */
:deep(.dark code) {
  color: #e2e8f0;
}

:deep(.dark pre code) {
  color: #e2e8f0;
  background: transparent;
}

/* 添加暗色主题下的引用块样式 */
:deep(.dark blockquote) {
  background-color: rgba(75, 85, 99, 0.2);
}

/* 平滑主题切换动画 */
:deep(*) {
  transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}
</style> 